function D_new=osl_channelrepair(S)

D=S.D;

data=spm2fieldtrip(D);

bch_list=badchannels(D);
A=chanlabels(D);
chan_names=A(bch_list);

B=sensors(D,S.modality);

cfg=[];
cfg.elec.pnt=B.elecpos;
cfg.elec.label=B.label;

lay = ft_prepare_layout(cfg, data);

cfg=[];
cfg.method        = 'triangulation';
cfg.layout        = lay;
cfg.channel       = B.label;
cfg.feedback      = 'no';

neighbours = ft_prepare_neighbours(cfg,data);

cfg=[];
cfg.method = 'nearest';
cfg.badchannel = chan_names;
cfg.missingchannel = [];
cfg.neighbours     = neighbours;
cfg.trials         = 'all';
cfg.elec.pnt=B.elecpos;
cfg.elec.label=B.label;
 
[interp] = channelrepair(cfg, data);

fname=fnamedat(D);

S=[];
S.D=D;
S.newname=[path(D) filesep 'C' fname(1:end-4) '.mat'];
D_new=spm_eeg_copy(S);

D_new(:,:,1)=interp.trial{1};
D_new=badchannels(D_new,[],zeros(1,size(D_new,1)));
D_new.save;
